/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.lczyfy.idcp.modules.sys.vueweb;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lczyfy.idcp.common.config.Global;
import com.lczyfy.idcp.common.persistence.Page;
import com.lczyfy.idcp.common.utils.Collections3;
import com.lczyfy.idcp.common.utils.ResponseCode;
import com.lczyfy.idcp.common.utils.ServerResponse;
import com.lczyfy.idcp.common.utils.StringUtils;
import com.lczyfy.idcp.common.web.BaseController;
import com.lczyfy.idcp.modules.sys.entity.*;
import com.lczyfy.idcp.modules.sys.service.OfficeService;
import com.lczyfy.idcp.modules.sys.service.SystemService;
import com.lczyfy.idcp.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 角色Controller
 * @author ThinkGem
 * @version 2013-12-05
 */
@Api(value = "role")
@RestController
@RequestMapping(value = "${apiPath}/sys/role")
public class RoleVueController extends BaseController {

	@Autowired
	private SystemService systemService;

    @Autowired
    private OfficeService officeService;
	@ApiOperation(value = "添加角色", notes = "")
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public ServerResponse<String>  save(@RequestBody Role role) {
	    if(StringUtils.isBlank(role.getId())){
            if (!"true".equals(checkName(role.getOldName(), role.getName()))){
                return ServerResponse.createByErrorMessage("失败, 角色名已存在");
            }
            if (!"true".equals(checkEnname(role.getOldEnname(), role.getEnname()))){
                return ServerResponse.createByErrorMessage("失败, 英文名已存在");
            }
        }
		if(!UserUtils.getUser().isAdmin()&&role.getSysData().equals(Global.YES)){
			return ServerResponse.createByErrorMessage("越权操作，只有超级管理员才能修改此数据！");
		}
		if(Global.isDemoMode()){
			return ServerResponse.createByErrorMessage("演示模式，不允许操作！");
		}
		if(StringUtils.isNotBlank(role.getOfficeId())){
			role.setOffice(officeService.get(role.getOfficeId()));
		}
		systemService.saveRole(role);
		return ServerResponse.createBySuccessMessage("保存角色" + role.getName() + "成功");
	}
    @ApiOperation(value = "获取角色列表", notes = "")
	@RequiresPermissions("sys:role:view")
	@RequestMapping(value = "search", method = RequestMethod.GET)
	public ServerResponse<Role> list() {
		List<Role> list = systemService.findAllRole();
		return new ServerResponse<Role>(ResponseCode.SUCCESS.getCode(),list) ;
	}
    @ApiOperation(value = "获取添加角色菜单列表", notes = "")
	@RequiresPermissions("sys:role:view")
    @RequestMapping(value = "roleMenu", method = RequestMethod.GET)
    public ServerResponse<Menu> Menu() {
        List<Menu> list = systemService.findAllMenu();;
        return new ServerResponse<Menu>(ResponseCode.SUCCESS.getCode(),list) ;
    }
    @ApiOperation(value = "获取添加部门菜单列表", notes = "")
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "roleOffice", method = RequestMethod.GET)
    public ServerResponse<Office> Office() {
        List<Office> list = officeService.findAll();;
        return new ServerResponse<Office>(ResponseCode.SUCCESS.getCode(),list) ;
    }
    @ApiOperation(value = "已选中角色分配的接口", notes = "")
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "selected/findById/{id}", method = RequestMethod.GET)
    public ServerResponse<List<Map<String, Object>>> selectedroles(@PathVariable String id) {
		List<User> userList = systemService.findVue(new User(new Role(id)));;
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Map<String, Object> map = Maps.newHashMap();
		map.put("userList",userList);
		map.put("selectIds",Collections3.extractToString(userList, "name", ","));
		map.put("officeList", officeService.findAll());
		mapList.add(map);
        return new ServerResponse(ResponseCode.SUCCESS.getCode(), mapList) ;
    }
    @ApiOperation(value = "删除角色", notes = "根据url的id来指定删除对象")
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "delete", method = RequestMethod.DELETE)
	public ServerResponse<String> delete(@RequestBody Role role) {
		if(!UserUtils.getUser().isAdmin() && role.getSysData().equals(Global.YES)){
            return ServerResponse.createByErrorMessage("越权操作，只有超级管理员才能修改此数据！");
		}
		if(Global.isDemoMode()){
            return ServerResponse.createByErrorMessage("演示模式，不允许操作！");
		}
			systemService.deleteRole(role);
            return ServerResponse.deleteBySuccessMessage("删除角色成功！");
	}

	/**
	 * 角色分配页面
	 * @param role
	 * @param model
	 * @return
	 */
	@ApiOperation(value = "角色分配页面", notes = "")
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "assign/findById/{id}",method = RequestMethod.GET)
	public ServerResponse<User> assign(@PathVariable String id) {
		List<User> userList = systemService.findVue(new User(new Role(id)));
		return new ServerResponse<User>(ResponseCode.SUCCESS.getCode(),userList) ;
	}
	@ApiOperation(value = "角色详情", notes = "")
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "findById/{id}",method = RequestMethod.GET)
	public ServerResponse<Role> findById(@PathVariable String id) {
		Role rolefindById = systemService.getRole(id);
		if(StringUtils.isNotBlank(rolefindById.getOffice().getId())){
			rolefindById.setOfficeId(rolefindById.getOffice().getId());
		}
		return new ServerResponse<Role>(ResponseCode.SUCCESS.getCode(),rolefindById) ;
	}
	@ApiOperation(value = "角色分配 -- 从角色中移除用户", notes = "")
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "outrole/{userId}/{roleId}",method = RequestMethod.DELETE)
	public ServerResponse<String> outrole(@PathVariable String userId,@PathVariable String roleId) {
		if(Global.isDemoMode()){
			return ServerResponse.createByErrorMessage("演示模式，不允许操作！");
		}
		Role role = systemService.getRole(roleId);
		User user = systemService.getUser(userId);
		if (UserUtils.getUser().getId().equals(userId)) {
			return ServerResponse.createByErrorMessage( "无法从角色【" + role.getName() + "】中移除用户【" + user.getName() + "】自己！");
		}else {
			if (user.getRoleList().size() <= 1){
				return ServerResponse.createByErrorMessage("用户【" + user.getName() + "】从角色【" + role.getName() + "】中移除失败！这已经是该用户的唯一角色，不能移除。");
			}else{
				Boolean flag = systemService.outUserInRole(role, user);
				if (!flag) {
					return ServerResponse.createByErrorMessage("用户【" + user.getName() + "】从角色【" + role.getName() + "】中移除失败！");
				}else {
					return ServerResponse.createBySuccessMessage("用户【" + user.getName() + "】从角色【" + role.getName() + "】中移除成功！");
				}
			}
		}
//		return "redirect:" + adminPath + "/sys/role/assign?id="+role.getId();
	}

	/**
	 * 角色分配
	 * @param role
	 * @param idsArr
	 * @param redirectAttributes
	 * @return
	 */
	@ApiOperation(value = "从角色中添加用户", notes = "")
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "assignrole/{id}", method = RequestMethod.PUT)
	public  ServerResponse<String>  assignRole(@PathVariable String id,@RequestBody String[] idsArr) {
	    Role role = systemService.getRole(id);
		if(Global.isDemoMode()){
			return ServerResponse.createByErrorMessage("演示模式，不允许操作！");
		}
		StringBuilder msg = new StringBuilder();
		int newNum = 0;
		for (int i = 0; i < idsArr.length; i++) {
			User user = systemService.assignUserToRole(role, systemService.getUser(idsArr[i]));
			if (null != user) {
				msg.append("新增用户【" + user.getName() + "】到角色【" + role.getName() + "】！");
				newNum++;
			}
		}
		return ServerResponse.createBySuccessMessage("已成功分配 "+newNum+" 个用户"+msg);
	}
	@ApiOperation(value = "验证角色名是否有效", notes = "")
	@RequiresPermissions("user")
	@RequestMapping(value = "checkName",method = RequestMethod.GET)
	public String checkName(String oldName, String name) {
		if (name!=null && name.equals(oldName)) {
			return "true";
		} else if (name!=null && systemService.getRoleByName(name) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证角色英文名是否有效
	 * @param oldName
	 * @param name
	 * @return
	 */
	@ApiOperation(value = "验证角色英文名是否有效", notes = "")
	@RequiresPermissions("user")
	@RequestMapping(value = "checkEnname",method = RequestMethod.GET)
	public String checkEnname(String oldEnname, String enname) {
		if (enname!=null && enname.equals(oldEnname)) {
			return "true";
		} else if (enname!=null && systemService.getRoleByEnname(enname) == null) {
			return "true";
		}
		return "false";
	}
	@ApiOperation(value = "根据部门officeId编号获取用户列表", notes = "")
	@RequiresPermissions("user")
	@RequestMapping(value = "user/{id}",method = RequestMethod.GET)
	public List<Map<String, Object>> users(@PathVariable String id) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		User user = new User();
		user.setOffice(new Office(id));
		Page<User> page = systemService.findUser(new Page<User>(1, -1), user);
		for (User e : page.getList()) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", 0);
			map.put("name", e.getName());
			mapList.add(map);
		}
		return mapList;
	}
}
